/* 审核用户 */
import React, { PureComponent } from 'react';
import { Table, Pagination, Form, Input, Button, Select, Cascader, DatePicker, Modal, message, Upload, Row, Col } from 'antd';
import { getAudit, deletePerson, auditPerson, getAuthority, uploadPersonAudit, downloadExcelWrongStudents, coverPeople, auditPayPerson } from '@/services/peoples'
import { getSubject } from '@/services/lessons'
import { getHandle, baseurl } from '@/services/baseurl'
import ShowModal from '../UserManagement/ShowModal'
import Authorized from '@/components/Authorized/Authorized'
import EditModal from '../UserManagement/EditModal'
import AddModal from './AddModal';
import { isAnte, isHangda, isBinhai,isZhongZheng,hasCompany } from '@/utils/utils';
import AnalyzeModal from '../UserManagement/AnalyzeModal'
import { withRouter } from "umi";
import { isZhengda } from '../../../utils/utils';
const { RangePicker } = DatePicker
class Index extends PureComponent<any, any> {
  constructor(props: any) {
    super(props);
    const userinfo = JSON.parse(localStorage.getItem('userinfo'));
    this.state = {
      dataSource: [],
      page: '',
      start_date: '',
      end_date: '',
      type: '1',
      searchName:'',
      name: '',
      duty: userinfo.student_type ? userinfo.student_type.split(',').map(Number) : [],
      currentPage: 1,
      count: 1,
      loading: true,
      selectedRowKeys: [],
      showVisible: false,
      currentRow: {},
      typeList: [],
      selectedRows: [],
      lessonsData: [],
      editVisible: false,
      password: '',
      confirmPassword: '',
      sexy: '', id_number: '',
      phone: '', lessons: '', subject: '', integral: '', exam_date: '', company: '',
      invoice: '',
      invoice_img: [],
      addVisible: false,
      warnVisible: false,
      uploadLoading: false,
      fileList: [],
      warnData: { id_number: [], id_numbers: [] },
      analyzeVisible: false,
      analyzeData: {},
      searchCompany: '',
      idcard:'',
      photo: '', id_card_front: '', id_card_back: '', diploma: '', family_register: '', month: '', year: ''
    }
  }
  renderList = (page: any) => {
    const { start_date, end_date, type, searchName, duty, selectedRows, searchCompany } = this.state;
    const { baoming } = this.props;
    const info = JSON.parse(localStorage.getItem('userinfo') || '{}');
    const power = info.types ? info.types.power : '';
    const noPower = power.indexOf('110') === -1 || power.indexOf('910') === -1;
    const arr: any = [];
    getAudit({ page, start_date, company: searchCompany, end_date, type, name:searchName, duty: noPower ? (duty[duty.length - 1] || '') : '', power: noPower ? '' : '110', baoming }).then(res => {
      if (!res) return;
      for (let i = 0; i < res.data.length; i++) {
        const item = res.data[i];
        for (let j = 0; j < selectedRows.length; j++) {
          const key = selectedRows[j];
          if (item.id === key) {
            arr.push(item)
          }
        }
      }

      this.setState({
        dataSource: res.data,
        count: res.count,
        loading: false,
        selectedRows: arr
      })
    })
  }
  changeTime = (e: any, str: object) => {
    this.setState({
      start_date: str[0],
      end_date: str[1]
    })
  };
  changeSearchDuty = (e: any) => {
    const student_type = JSON.parse(localStorage.getItem('userinfo') || '{}').student_type;
    if (student_type) {
      const duty = student_type.split(',').map(Number);
      const eStrging = e.join(',')
      if (!e[0] || e.length < duty.length || (e.length === duty.length && eStrging !== student_type)) {
        return this.setState({
          duty
        })
      }
    }
    this.setState({
      duty: e
    })
  }
  changeValue = (e: any, name: string) => {
    this.setState({
      [name]: e
    })
  }
  changeValueWithTarget = (e: any, name: string) => {
    this.setState({
      [name]: e.target.value
    })
  }
  changeExamDate = (e: any, exam_date: string) => {
    this.props.changeExamDate(exam_date)
  }
  searchHandle = () => {
    this.setState({
      loading: true,
      currentPage: 1
    }, () => {
      this.renderList(1)
    })
  }
  changePage = (e: any) => {
    this.setState({
      currentPage: e,
      loading: true
    })
    this.renderList(e)
  }
  showModal = (row: any) => () => {
    this.showRow(row)
    this.setState({
      currentRow: row,
      showVisible: true
    })
  }
  hideModal = () => {
    this.setState({
      showVisible: false
    })
  }

  deletePerson = () => {
    const ids = [452, 453, 454, 455, 456, 457, 458, 459, 460, 461, 462, 463, 464, 465, 466, 467, 468, 469, 470, 471, 472, 473, 474, 475, 476, 477, 478, 479, 480, 481, 482, 483, 486, 487]
    const { selectedRowKeys, currentPage } = this.state;
    // for (let i = 0; i < selectedRowKeys.length; i++) {
    //   const item = selectedRowKeys[i];
    //   if (window.location.host === 'xuexi.shejiyuan.com') {
    //     for (let j = 0; j < ids.length; j++) {
    //       if (item == ids[j]) {
    //         return message.error('存在无法删除的账号')
    //       }
    //     }
    //   }

    // }
    Modal.confirm({
      okText: '确定',
      cancelText: '取消',
      title: '提示',
      content: '确定删除选中的用户？',
      onOk: () => {
        deletePerson({ id: selectedRowKeys }).then(res => {
          if (res.status === 1) {
            message.success('已删除')
            this.renderList(currentPage)
            const name = localStorage.getItem('name')
            const operation = name + '删除了' + selectedRowKeys.length + '名学员'
            getHandle({ operation })
            this.setState({
              selectedRowKeys: []
            })
          } else {
            message.error('删除失败')
          }
        })
      }
    })
  }
  auditPerson = () => {
    const { selectedRowKeys, currentPage, selectedRows } = this.state;
    const { baoming } = this.props;
    if (selectedRows.length === 1 && !selectedRows[0].student_type) {
      this.showEditPerson(selectedRows[0])()
      return;
    }
    Modal.confirm({
      okText: '确定',
      cancelText: '取消',
      title: '提示',
      content: '确定审核选中的用户？',
      onOk: () => {
        let uid = [];
        for (let i = 0; i < selectedRows.length; i++) {
          const item = selectedRows[i];
          if (!item.student_type) {
            uid.push(item.id)
          }
        }
        const student_type = JSON.parse(localStorage.getItem('userinfo') || '{}').student_type;
        const auditHandle = () => {
          message.success('已审核')
          this.renderList(currentPage)
          const name = localStorage.getItem('name')
          let type = ''
          if (baoming === '1') {
            type = '名报名用户'
          } else {
            type = '名学员'
          }
          const operation = name + '审核了' + selectedRowKeys.length + type
          getHandle({ operation })
          this.setState({
            selectedRows: [],
            selectedRowKeys: [],
          })
        }
        if (baoming === '1'&&isZhongZheng()) {
          return auditPayPerson({ id: selectedRowKeys, audit_status: '2' }).then(res => {
            auditHandle()
          })
        }
        auditPerson({ id: selectedRowKeys, student_type: student_type !== null ? student_type : '', uid }).then(res => {
          auditHandle()
        })
      }
    })
  }
  componentDidMount() {
    this.renderList(1)
    getAuthority({ name: '' }).then(res => {
      this.setState({
        typeList: res
      })
    })
    getSubject().then(res => {
      if (!res || !res[0]) return;
      let data = JSON.stringify(res);
      data = data
        .replace(/id/g, 'value')
        .replace(/pvalue/g, 'pid')
        .replace(/"children":/g, '"checkable":false,"selectable":false,"children":')
        .replace(/"checkable":false,"selectable":false,"children":\[\]/g, '"children":[]')
      this.setState({
        lessonsData: JSON.parse(data)
      })
    })
  }
  showRow = (row: any) => {
    const {
      id_number,
      type,
      student_type,
      sexy,
      duty, name, subject, subjects, phone, integral, exam_date, invoice, invoice_img, company,idcard,photo, id_card_front, id_card_back, diploma, family_register, month, year  } = row;
      const {baoming} =this.props;
    const userinfo = JSON.parse(localStorage.getItem('userinfo') || '{}');
    if(baoming==='0'){
      this.setState({
        idcard
      })
    }
    this.setState({
      currentRow: row,
      id_number,
      company,
      type: type === '考生' ? 2 : type,
      student_type: student_type ? student_type.split(',').map(Number) : userinfo.student_type ? userinfo.student_type.split(',').map(Number) : [],
      sexy: sexy ? sexy + '' : '',
      duty: duty ? duty * 1 : '',
      name,
      phone: Number(phone),
      lessons: subject ? subject.split(',').map(Number) : [],
      subject: subjects,
      integral,
      photo, id_card_front, id_card_back, diploma, family_register, month, year,
      selectedRows: [row],
      selectedRowKeys: [row.id],
      exam_date: exam_date && exam_date !== '0000-00-00' ? exam_date : '',
      uploadVisible: false,
      invoice,
      invoice_img: [{
        uid: '-1',
        name: invoice_img,
        status: 'done',
        url: baseurl + invoice_img,
        thumbUrl: baseurl + invoice_img,
      }]
    })
  }
  showEditPerson = (row: any) => () => {
    this.showRow(row)
    this.setState({
      editVisible: true,
      idcard:''
    })
  }

  hideEditPerson = () => {
    this.setState({
      editVisible: false,
      password: '',
      confirmPassword: '',
      // selectedRows: [],
      // selectedRowKeys: [],
      name: ''
    })
  }
  changeFile = (info: any, name: string) => {
    let fileList = [...info.fileList];
    fileList = fileList.slice(-1);
    fileList = fileList.map(file => {
      if (file.response) {
        file.url = file.response.url;
      }
      return file;
    });
    this.setState({ [name]: fileList });
  };
  showAddPerson = () => {
    this.setState({ addVisible: true })
  }
  hideAddPerson = () => {
    this.setState({ addVisible: false })
  }
  showUpload = () => {
    this.setState({
      uploadVisible: true
    })
  }
  uploadPerson = () => {
    const { fileList } = this.state;
    if (!fileList[0]) {
      return message.error('请上传文件')
    }
    this.setState({
      uploadLoading: true
    })

    uploadPersonAudit({ file: fileList[0].originFileObj }).then(res => {
      const id_number = res.id_number;
      const id_numbers = res.id_numbers;
      const id_numberss = res.id_numberss;
      let warnData = { id_number: [], id_numbers: [], id_numberss: [] }
      this.setState({
        uploadVisible: false
      })
      if (res.num > 0) {
        const name = localStorage.getItem('name');
        const operation = name + '批量增加了' + res.num + '名学员'
        getHandle({ operation })
      }
      for (const key in id_number) {
        const item = id_number[key];
        warnData.id_number.push(item)
      }
      for (const k in id_numbers) {
        const item = id_numbers[k];
        if (item.id) {
          warnData.id_numbers.push(item)
        }
      }
      for (const k in id_numberss) {
        const item = id_numberss[k];
        if (item.id) {
          warnData.id_numberss.push(item)
        }
      }
      if (warnData.id_number.length > 0 || warnData.id_numbers.length > 0 || warnData.id_numberss.length > 0) {
        this.setState({
          warnVisible: true,
          uploadLoading: false,
          warnData
        })
        return
      }
      message.success('上传成功')

      this.setState({
        uploadVisible: false,
        fileList: [],
        uploadLoading: false
      })
    })
  }
  hideUpload = () => {
    this.setState({
      uploadVisible: false
    })
  }
  hideWarn = () => {
    this.setState({
      warnVisible: false
    })
  }
  downloadExcelWrongStudents = () => {
    const uid = localStorage.getItem('id');
    const { warnData } = this.state
    warnData.uid = uid;
    downloadExcelWrongStudents(warnData).then(res => {
      window.open(baseurl + 'index/index/derive_repetition?uid=' + uid)
    })
  }
  changeFiles = (info: any) => {
    const fileList = info.fileList;
    let file = null;
    if (fileList.length > 1) {
      file = [fileList[fileList.length - 1]];
    } else {
      file = fileList
    }
    this.setState({
      fileList: file
    })
  }
  coverOrigin = () => {
    const { id_number, id_numbers, id_numberss } = this.state.warnData;
    let idNumberList: any = [];
    const wrongUsers = [...id_numbers, ...id_numberss];

    if (wrongUsers[0]) {
      id_number.map((item: any) => {
        wrongUsers.map(wrong => {
          if (item.id !== wrong.id) {
            idNumberList.push(item)
          }
        })

      })
    } else {
      id_number.map((item: any) => {
        idNumberList.push(item)
      })
    }
    Modal.confirm({
      title: '提示',
      content: '确定要覆盖原有用户？',
      onOk: () => {
        if (!idNumberList[0]) return message.error('没有可以覆盖的用户')
        coverPeople({ id_number: idNumberList }).then(res => {
          if (res.status === 1) {
            message.success('已覆盖')
            this.renderList(1);
          } else {
            message.error('操作失败')
          }
        })
      }
    })
  }
  componentWillUnmount = () => {
    this.setState = (state, callback) => {
      return;
    };
  }
  showAnalyze = (row: any) => () => {
    this.setState({
      analyzeVisible: true,
      analyzeData: row
    })
  }
  hideAnalyze = () => {
    this.setState({
      analyzeVisible: false
    })
  }
  render() {
    const { options, positionData } = this.props;
    const { currentRow, dataSource, count, currentPage, loading, selectedRowKeys, typeList, lessonsData, duty, addVisible, uploadLoading,
      uploadVisible, warnVisible, fileList, warnData, analyzeVisible, analyzeData
    } = this.state;
    const student_types = currentRow.student_type && currentRow.student_type.split(',').map(Number)
    const columns = [
      {
        title:'编号',
        dataIndex:'idcard'
      },
      {
        title: '准考证号',
        dataIndex: 'id_number',
        render: (id_number: any, row: any) => {
          return row.baoming === 1 ? <p style={{ color: "red" }}>{id_number + '(在线报名)'}</p> : id_number
        }
      },
      {
        title: '姓名',
        dataIndex: 'name',
        render: (name: any, row: any) => {
          return row.baoming === 1 ? <p style={{ color: "red" }}>{name}</p> : name
        }
      },
      {
        title: hasCompany() ? '公司名称' : '部门',
        dataIndex: 'student_types',
        render: (student_types: any, row: any) => {
          return hasCompany() ? (row.baoming === 1 ? <p style={{ color: "red" }}>{row.company}</p> : row.company) : (row.baoming === 1 ? <p style={{ color: "red" }}>{student_types}</p> : student_types)
        }
      },

      {
        title: '科目',
        dataIndex: 'subjects',
        render: (subjects: any, row: any) => {
          return row.baoming === 1 ? <p style={{ width: 200, color: "red" }}>{subjects}</p> : <p style={{ width: 200 }}>{subjects}</p>
        }
      },
      {
       
        title: isAnte()?'备注':'电话号码',
        dataIndex: 'phone',
        render: (phone: any, row: any) => {
          return row.baoming === 1 ? <p style={{ color: "red" }}>{(Number(phone) || '')}</p> : (Number(phone) || '')
        }
      },
      {
        title: '备注',
        dataIndex: 'remarks',
        render: (remarks: any, row: any) => {
          return row.baoming === 1 ? <p style={{ color: "red" }}>{(Number(remarks) || '')}</p> : (Number(remarks) || '')
        }
      },
      {
        title: '级别',
        dataIndex: 'type',
        render: (type: any, row: any) => {
          return row.baoming === 1 ? <p style={{ color: "red" }}>{type}</p> : type
        }
      },
      // {
      //   title: '是否交费',
      //   dataIndex: 'is_pay',
      //   render: (is_pay: any, row: any) => {
      //     if (is_pay == 0) {
      //       return row.baoming === 1 ? <p style={{color:"red"}}>未支付</p> : '未支付'
      //     } else if (is_pay == 1) {
      //       return row.baoming === 1 ? <p style={{color:"red"}}>已支付</p> : '已支付'
      //     } else {
      //       return row.baoming === 1 ? <p style={{color:"red"}}>导入人员</p> : '导入人员'
      //     }
      //   }
      // },
      {
        title: '添加时间',
        dataIndex: 'created_at',
        render: (created_at: any, row: any) => {
          return row.baoming === 1?<p style={{color:"red"}}>{(row.created_ats || created_at)}</p>:(row.created_ats || created_at)
        }
      },
      {
        title: '操作',
        dataIndex: 'id',
        key: 'id',
        render: (id: any, row: any) => {
          return <React.Fragment>
            <a onClick={this.showAnalyze(row)}>统计</a>
            <a onClick={this.showModal(row)} style={{ margin: '0 20px' }}>查看</a>
            <Authorized authority={[103, 903]}>
              <a onClick={this.showEditPerson(row)}>修改</a>
            </Authorized>
          </React.Fragment>;
        },
      },
    ];
    if (isHangda()) {
      columns.splice(4, 1)
    }
    const {baoming} = this.props;
    if (!isZhongZheng()||baoming==='1') {//如果不是中正或者是报名页就不需要编号了
      columns.splice(0, 1)
    }
    // const tab = this.props.match.params.tab;
    // if(tab==='5'&&isBinhai()){
    //   columns.splice(3,0,{
    //     title: 'is_pay',
    //     dataIndex: 'is_pay',
    //     return: (is_pay: any) => {
    //       return <p style={{ color: is_pay === 0 ? "red" : '' }}>{is_pay?'已交费':'未交费'}</p>
    //     }
    //   })
    // }
    const rowSelection = {
      selectedRowKeys,
      onChange: (selectedRowKeys: any, selectedRows: any) => {
        this.setState({
          selectedRowKeys,
          selectedRows
        })
      },
    };


    return (
      <div>
        <div style={{ overflow: 'hidden' }}>
          <Form layout="inline" style={{ marginBottom: 20, float: 'right' }}>
            <Form.Item>
              <RangePicker picker="date" onChange={this.changeTime} />
            </Form.Item>
            <Form.Item>
              <Select style={{ width: 150 }} placeholder="请选择搜索类别" onChange={(e: any) => this.changeValue(e, 'type')} defaultValue="1">
                <Select.Option value=" " key="3">全部</Select.Option>
                <Select.Option value="1" key="1">姓名</Select.Option>
                <Select.Option value="2" key="2">准考证号</Select.Option>
              </Select>
              <Input style={{ width: 150 }} placeholder="请输入搜索信息" onChange={(e: any) => this.changeValueWithTarget(e, 'searchName')} />
            </Form.Item>
            {
              isBinhai()||isZhengda() ? <Form.Item>
                <Input placeholder="请输入搜索公司" onChange={(e: any) => this.changeValueWithTarget(e, 'searchCompany')} />
              </Form.Item> : <Form.Item>
                <Cascader placeholder="请选择搜索部门" options={options} value={duty} changeOnSelect onChange={this.changeSearchDuty} />
              </Form.Item>
            }
            <Form.Item>
              <Button type="primary" onClick={this.searchHandle}>查询</Button>
            </Form.Item>
            {isAnte() && <Authorized authority={[112]}>
              <Form.Item>
                <Button type="primary" style={{ backgroundColor: '#029b0d', borderColor: "#029b0d" }} onClick={this.showAddPerson}>增加</Button>
              </Form.Item>
              <Form.Item>
                <Button type="primary" style={{ backgroundColor: '#029b0d', borderColor: "#029b0d" }} onClick={this.showUpload} >批量上传</Button>
              </Form.Item>
            </Authorized>}
          </Form>
        </div>
        <Table
          columns={columns}
          pagination={false}
          rowKey="id"
          scroll={{ x: 1400 }}
          rowSelection={rowSelection}
          dataSource={dataSource}
          loading={loading}
          footer={() => (
            <React.Fragment>
              {
                isAnte() && <Authorized authority={[113, 913]}>
                  <Button type="primary" style={{ marginLeft: 5, marginRight: 20 }} onClick={this.auditPerson}>审核所选</Button>
                </Authorized>
              }
              {
                !isAnte() &&  <Authorized authority={[120, 920]}> <Button type="primary" style={{ marginLeft: 5, marginRight: 20 }} onClick={this.auditPerson}>审核所选</Button></Authorized>
              }
              <Authorized authority={[105, 905]}>
                <Button type="primary" danger onClick={this.deletePerson}>删除所选</Button>
              </Authorized>
            </React.Fragment>
          )}
        ></Table>
        <Pagination
          showQuickJumper
          showSizeChanger={false}
          locale="zh-CN"
          total={count}
          current={currentPage}
          onChange={this.changePage}
          style={{ float: 'right', marginTop: 25 }}
          showTotal={(total, range) => { return `第${range[0]}条-第${range[1]}条，共 ${total} 条` }}
        />
        <AddModal
          addVisible={addVisible}
          renderList={this.renderList}
          currentPage={currentPage}
          options={options}
          hideAddPerson={this.hideAddPerson}
          positionData={positionData}
          typeList={typeList}
          lessonsData={lessonsData}
        />
        <EditModal
          data={{ ...this.state, ...this.props }}
          hideEditPerson={this.hideEditPerson}
          changeFile={this.changeFile}
          changeValue={this.changeValue}
          changeValueWithTarget={this.changeValueWithTarget}
          changeExamDate={this.changeExamDate}
          renderList={this.renderList}
        />
        <ShowModal
          data={{ ...this.state, ...this.props }}
          renderList={this.renderList}
          hideShowPerson={this.hideModal}
        />
        <AnalyzeModal visible={analyzeVisible} onHide={this.hideAnalyze} data={analyzeData} />
        <Modal confirmLoading={uploadLoading} title="批量上传" okText="批量上传" visible={uploadVisible} onCancel={this.hideUpload} onOk={this.uploadPerson}>
          <Form>
            <Form.Item label="上传用户列表">
              <Upload accept=".xlsx,.xls" beforeUpload={() => { return false }} onChange={this.changeFiles} fileList={fileList}>
                <Button type="primary">上传EXCEL列表</Button>
              </Upload>
              <div style={{ marginTop: 20 }}>
                <a href={baseurl + 'Template.xls'}><Button>下载用户模板</Button></a>
              </div>
            </Form.Item>
          </Form>
        </Modal>
        <Modal title="上传反馈" visible={warnVisible} onCancel={this.hideWarn} onOk={this.hideWarn}>
          {
            warnData.id_number && warnData.id_number[0] && <b>以下用户准考证号码重复，请审核后导入
              <Button type="primary" onClick={this.coverOrigin} style={{ marginLeft: 10 }}>覆盖原有用户</Button></b>
          }
          {
            warnData.id_number && warnData.id_number.map(item => {
              return <Row key={item.id}>
                <Col span={5}>{item.name} </Col>
                <Col span={10}>{item.id}</Col>
              </Row>
            })
          }
          {
            warnData.id_number && <br />
          }
          {
            warnData.id_numbers && warnData.id_numbers[0] && <b>以下用户所在部门还未设置，请审核后导入</b>
          }
          {
            warnData.id_numbers && warnData.id_numbers.map(item => {
              return <Row key={item.id}>
                <Col span={5}>{item.name} </Col>
                <Col span={10}>{item.id}</Col>
              </Row>
            })
          }
          {
            warnData.id_numbers && <br />
          }
          {
            warnData.id_numberss && warnData.id_numberss[0] && <b>以下用户培训科目设置错误，请审核后导入</b>
          }
          {
            warnData.id_numberss && warnData.id_numberss.map(item => {
              return <Row key={item.id}>
                <Col span={5}>{item.name} </Col>
                <Col span={10}>{item.id}</Col>
              </Row>
            })
          }
          <Button type="primary" style={{ backgroundColor: '#fca53e' }} onClick={this.downloadExcelWrongStudents}>导出有误信息用户excel列表</Button>
        </Modal>
      </div>
    );
  }
}

export default withRouter(Index);
